package myindexer

import (
    "fmt"
    "myutils"
)

type Indexer struct {
    indexName string           // 索引名称
    docId uint64                 // 文档ID
    idx map[string][]myutils.DocInfo  // 倒排文件
    pfl []string                  // 正排文件
}

func NewIndexer(indexName string) *Indexer{
    return &Indexer{indexName:indexName, docId:0, idx:make(map[string][]myutils.DocInfo), pfl:make([]string, 0)}
}

func (this *Indexer) AddDocument(content string) error {
    if len(content) == 0 {
        return fmt.Errorf("content lens is zore")
    }

    terms := myutils.GSegmenter.Segment(content, true)

    if len(terms) > 0{
        for _, v := range terms {
            if _, ok := this.idx[v]; !ok {
                this.idx[v] = make([]myutils.DocInfo, 0)
            }
            this.idx[v] = append(this.idx[v], myutils.DocInfo{DocId:this.docId})
        }
    }

    this.pfl = append(this.pfl, content)
    this.docId++

    return nil
}

func (this *Indexer) SyncIndex() error {
    if err := myutils.WriteJsonToFile(this.idx, myutils.ROOT + "index.idx"); err != nil {
        return err
    }

    if err := myutils.WriteJsonToFile(this.pfl, myutils.ROOT + "index.pfl"); err != nil {
        return err
    }

    return nil
}